package com.samsung.booksmanagement;

import java.util.ArrayList;

import com.example.goup17booksmanagement.R;

import android.content.Context;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class BookAdapter extends ArrayAdapter<Book> {
	private ArrayList<Book> bookList;
	private Context mContext;

	public BookAdapter(Context context, ArrayList<Book> objects) {
		super(context, R.layout.book_row, objects);
		// TODO Auto-generated constructor stub
		this.mContext = context;
		this.bookList = objects;
	}
	
	private class BookHolder {
		TextView name;
		ImageView avatar;
	}
	
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		BookHolder holder = null;

		if (convertView == null) {
			LayoutInflater inflater = (LayoutInflater) mContext
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			convertView = inflater.inflate(R.layout.book_row, parent, false);

			holder = new BookHolder();
			holder.name = (TextView) convertView.findViewById(R.id.tvBookDetail);
			holder.avatar = (ImageView) convertView
					.findViewById(R.id.imgAvatar);
			convertView.setTag(holder);
		} else {
			holder = (BookHolder) convertView.getTag();
		}

		Book tempBook = bookList.get(position);
		holder.name.setText(tempBook.getName());

		Uri uriTemp = null;
		if (tempBook.getImage() != null)
			uriTemp = Uri.parse(tempBook.getImage());
		
		if ( uriTemp != null ) {
			holder.avatar.setImageURI(uriTemp);
		} else 
			holder.avatar.setImageResource(R.drawable.book2);
		holder.avatar.setTag(tempBook.getImage());
		return convertView;
	}

}
